package com.goodmr.passport.device;

import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * 设备数据逻辑服务
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Service
public class DeviceDaoImpl implements DeviceDao {

    private final DeviceRepository deviceRepository;

    @Autowired
    public DeviceDaoImpl(DeviceRepository deviceRepository) {
        this.deviceRepository = deviceRepository;
    }

    /**
     * 创建设备信息
     *
     * @param model 设备model
     * @return 设备信息
     */
    @Override
    public DeviceModel generate(@NonNull DeviceModel model) {

        model.setIsSecured(SecureEnum.YES);

        return insert(model);
    }

    /**
     * 添加设备信息
     *
     * @param model 设备model
     * @return 设备信息
     */
    @Override
    public DeviceModel add(@NonNull DeviceModel model) {

        model.setIsSecured(SecureEnum.NO);

        return insert(model);
    }

    /**
     * 设备是否已认证
     *
     * @param model 设备model
     * @return 设备信息
     */
    @Override
    public boolean isSecured(@NonNull DeviceModel model) {

        boolean secured = false;

        long accountId = model.getAccountId();
        String name = model.getName().getValue();
        String token = model.getToken();

        DeviceEntity entity = deviceRepository.findByAccountIdAndNameAndToken(accountId, name, token);

        if (null == entity) {
            add(model);
        } else {
            secured = entity.getIsSecured() == SecureEnum.YES.getValue();
        }

        return secured;
    }

    /**
     * 创建设备信息
     *
     * @param model 设备model
     * @return 设备信息
     */
    private DeviceModel insert(@NonNull DeviceModel model) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        model.setCreatedAt(timestamp);
        model.setUpdatedAt(timestamp);

        DeviceEntity deviceEntity = new DeviceEntity();

        BeanUtils.copyProperties(model, deviceEntity);

        deviceEntity.setName(model.getName().getValue());
        deviceEntity.setIsSecured(model.getIsSecured().getValue());

        deviceEntity = deviceRepository.save(deviceEntity);

        model.setId(deviceEntity.getId());

        return model;
    }
}
